<template>
  <div ref="chartRef" class="chart"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { fetchTopProductsStock } from '@/api/data';

const chartRef = ref(null);
let chartInstance = null;

const option = ref({
  title: {
    text: '热门商品库存情况',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [],
    bottom: 0
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '12%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    name: '库存量'
  },
  series: []
});

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(option.value);
    
    // 响应式调整大小
    const resizeObserver = new ResizeObserver(() => {
      chartInstance?.resize();
    });
    resizeObserver.observe(chartRef.value);
    
    // 组件卸载时取消观察
    onBeforeUnmount(() => {
      resizeObserver.disconnect();
      chartInstance?.dispose();
    });
  }
};

// 获取数据并更新图表
const updateChart = async () => {
  const data = await fetchTopProductsStock();
  const products = data.map(item => item.productName);
  const dates = Array.from(new Set(data.flatMap(item => item.stockData.map(s => s.date))));
  
  option.value.xAxis.data = dates;
  option.value.legend.data = products;
  
  option.value.series = products.map(product => {
    const productData = data.find(item => item.productName === product);
    return {
      name: product,
      type: 'line',
      data: dates.map(date => {
        const stockItem = productData.stockData.find(s => s.date === date);
        return stockItem ? stockItem.stock : 0;
      }),
      smooth: true
    };
  });
  
  if (chartInstance) {
    chartInstance.setOption(option.value);
  }
};

onMounted(() => {
  initChart();
  updateChart();
});

// 监听option变化（如果需要动态更新）
watch(option, (newVal) => {
  if (chartInstance) {
    chartInstance.setOption(newVal, true);
  }
}, { deep: true });
</script>

<style scoped>
.chart {
  height: 100%;
  width: 100%;
  min-height: 400px; /* 确保图表有最小高度 */
}
</style>